package main

import (
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"hhos-mdijounery-server/api"
	"hhos-mdijounery-server/dao"
	"hhos-mdijounery-server/global"
	"hhos-mdijounery-server/library"
	midjourneyServer "hhos-mdijounery-server/proto"
	"hhos-mdijounery-server/service"
	"net"
	"net/http"
	"strconv"
)

var (
	dsn   = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", global.CONFIG.Mysql.User, global.CONFIG.Mysql.Password, global.CONFIG.Mysql.Host, global.CONFIG.Mysql.Port, global.CONFIG.Mysql.DbName)
	db, _ = gorm.Open(mysql.Open(dsn), &gorm.Config{})
)

func main() {

	// 初始化日志输出目录
	listen, err := net.Listen("tcp", global.CONFIG.Server.Host+":"+strconv.Itoa(global.CONFIG.Server.Port))
	if err != nil {
		global.Logger.Error("failed to listen: %v", zap.Error(err))
	}

	cert, err := credentials.NewServerTLSFromFile(global.Path(global.CONFIG.TLS.CertFile), global.Path(global.CONFIG.TLS.KeyFile))
	if err != nil {
		global.Logger.Error("failed to load key pair:", zap.Error(err))
	}

	options := []grpc.ServerOption{
		grpc.Creds(cert),
	}

	server := grpc.NewServer(options...)
	midjourneyDao := dao.NewMidjourneyDAO(db)
	midjourneyApi := library.NewMidJourneyApi()
	midjourneyService := service.NewMidjourney(midjourneyDao, midjourneyApi)
	midjourneyServer.RegisterMidjourneyServer(server, midjourneyService)
	// 启动接收回调服务
	go httpServer()
	global.Logger.Error("server listening at:", zap.Any("listen.Addr", listen.Addr()))

	if err := server.Serve(listen); err != nil {
		global.Logger.Error("failed to serve:", zap.Error(err))
	}
}

func httpServer() {
	var address = fmt.Sprintf("%s:%d", global.CONFIG.HttpServer.Host, global.CONFIG.HttpServer.Port)
	global.Logger.Error("http-server listening at ", zap.String("address", address))

	http.HandleFunc("/callback", api.Callback) // 接收回调请求

	err := http.ListenAndServe(address, nil)
	if err != nil {
		global.Logger.Error("err", zap.Error(err))
	}
}
